package com.app.aipass.activity;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.Manifest;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

//import com.example.csc.BR;
import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.databinding.ActivityTabBarBinding;
import com.app.aipass.entity.Message;
import com.app.aipass.fragment.main.FundFragment;
import com.app.aipass.fragment.main.MyFragment;
import com.app.aipass.fragment.main.NewMarketFragment;
import com.app.aipass.fragment.main.TransactionFragment;
import com.app.aipass.utils.PermissionUtils;
import com.app.aipass.utils.ToastUtils;
import com.app.aipass.utils.Utils;

import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.RxBus;

public class MainActivity  extends BaseActivity<ActivityTabBarBinding, BaseViewModel> {

    protected Fragment mContent = new Fragment();
    private FragmentManager mFragmentManager;
    private NewMarketFragment marketFragment;
    private TransactionFragment transactionFragment;
    private FundFragment fundFragment;
    private MyFragment myFragment;
    //记录点击位置
    private int old = 0;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_tab_bar;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    //    private Disposable mSubscription;
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        if(mSubscription != null)
//        {
//            RxSubscriptions.remove(mSubscription);
//        }
//    }
    @Override
    public void initData() {
//        StatusBarUtil.setStatusBarMode(this, false,R.color.app_bg_color);
//        mSubscription = RxBus.getDefault().toObservable(Message.class)
//                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
//                .subscribe(new Consumer<Message>() {
//                    @Override
//                    public void accept(final Message message) throws Exception {
//                        Log.e("TAG","=======MainActivity========message=============="+message.getName());
//                        if(message.getName().equals("start_login"))
//                        {
//                            navigationController.setSelect(3);
//                            commitAllowingStateLoss(3);
//                        }
//                    }
//                });
//        //将订阅者加入管理站
//        RxSubscriptions.add(mSubscription);

        //初始化Fragment
        initFragment();
        //初始化底部Button
        initBottomTab();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        statusBarTransparent();
//        Log.e("TAG", "=====123123====onCreate====================");
//        Intent intent = getIntent();
//        if(intent != null)
//        {
//            Log.e("TAG", "=========onCreate============intent========");
//            if(intent.hasExtra("token"))
//            {
//                Log.e("TAG", "=========onCreate============token========"+intent.getStringExtra("token"));
//            }
//        }
//        Log.e("TAG", "=====123123====onCreate====MainActivity====1111====token========"+getIntent().getStringExtra("token"));
//        getToken(getIntent());
        PermissionUtils.with(this)
                .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .addPermission(Manifest.permission.CAMERA)
//                .addPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
//                .addPermission(Manifest.permission.ACCESS_FINE_LOCATION)
//                .addPermission(Manifest.permission.READ_PHONE_STATE)
                .initPermission().size();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setIntent(intent);
//        if(intent != null)
//        {
//            if(intent.hasExtra("token"))
//            {
//                Log.e("TAG", "=====123123====onNewIntent============token========"+intent.getStringExtra("token"));
//                ShareUtil.getInstance().save(ShareUtil.ACCESS_TOKEN,intent.getStringExtra("token"));
//                RxBus.getDefault().post(new Message("start_login",""));
//            }
//        }
//    }
//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        Log.e("TAG", "=====123123====onNewIntent====MainActivity====1111====token========"+intent.getStringExtra("token"));
//        setIntent(intent);
//        getToken(intent);
//    }
//    private void getToken(Intent intent)
//    {
//        if(intent != null)
//        {
//            Log.e("TAG", "=====123123====getToken=====2222====MainActivity===token========"+intent.getStringExtra("token"));
//            if(intent.hasExtra("token"))
//            {
//                Log.e("TAG", "=====123123====getToken=====3333====MainActivity===token========"+intent.getStringExtra("token"));
//                ShareUtil.getInstance().save(ShareUtil.ACCESS_TOKEN,intent.getStringExtra("token"));
//                RxBus.getDefault().post(new Message("start_login",""));
////                isGetToken = true;
//            }
//        }
//    }

    @Override
    public void onCreatePre() {
        super.onCreatePre();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            getWindow().setStatusBarColor(Color.BLACK);
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }
//        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    @Override
    public void onCreateAfter() {
        super.onCreateAfter();
//        setWhiteStatusBar(true);

    }

    private void initFragment() {
        marketFragment = new NewMarketFragment();
        transactionFragment = new TransactionFragment();
        fundFragment = new FundFragment();
        myFragment = new MyFragment();
    }

    private void initBottomTab() {
        mFragmentManager = getSupportFragmentManager();
        binding.mainMarketBtn.setOnClickListener(v -> {
            old = 0;
            switchFragment(marketFragment, "MarketFragment");
            RxBus.getDefault().post(new Message("MainActivity_index_" + old, ""));
        });

        binding.mainTransactionBtn.setOnClickListener(v -> {
            old = 1;
            switchFragment(transactionFragment, "TransactionFragment");
            RxBus.getDefault().post(new Message("MainActivity_index_" + old, ""));
        });

        binding.mainAssetsBtn.setOnClickListener(v -> {
            if (!Utils.isLogin()) {
                switch (old){
                    case 0:
                        binding.mainMarketBtn.setSelected(true);
                        break;
                    case 1:
                        binding.mainTransactionBtn.setSelected(true);
                        break;
                    case 3:
                        binding.mainMineBtn.setSelected(true);
                        break;
                }
                return;
            }
            switchFragment(fundFragment, "FundFragment");
            old = 2;
            RxBus.getDefault().post(new Message("MainActivity_index_" + old, ""));
        });

         binding.mainMineBtn.setOnClickListener(v -> {
             old = 3;
             switchFragment(myFragment, "MineFragment");
             RxBus.getDefault().post(new Message("MainActivity_index_" + old, ""));
         });

         switchFragment(marketFragment,"MarketFragment");
         binding.mainMarketBtn.setSelected(true);


//        navigationController = binding.pagerBottomTab.material()
//                .addItem(R.mipmap.icon_main_market, R.mipmap.icon_main_market_select, "", ContextCompat.getColor(this, R.color.my_color_3212CF))
//                .addItem(R.mipmap.icon_main_transaction, R.mipmap.icon_main_transaction_select, "", ContextCompat.getColor(this, R.color.my_color_3212CF))
//                .addItem(R.mipmap.zichan, R.mipmap.zichan_select, "资产", ContextCompat.getColor(this, R.color.my_color_3212CF))
////                .addItem(R.mipmap.wode_select,R.mipmap.yingyong, "订单详情",ContextCompat.getColor(this,R.color.colorAccent))
//                .addItem(R.mipmap.my, R.mipmap.my_select, "我的", ContextCompat.getColor(this, R.color.my_color_3212CF))
//                .setDefaultColor(ContextCompat.getColor(this, R.color.app_bg_color))//textColorVice
//                .build();
//        //底部按钮的点击事件监听
//        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
//            @Override
//            public void onSelected(int index, int old) {
////                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
////                transaction.replace(R.id.frameLayout, mFragments.get(index));
////                transaction.commitAllowingStateLoss();
//                if (index == 2) {
//                    if (!Utils.isLogin()) {
//                        navigationController.setSelect(old);
//                        return;
//                    }
//                }
//                commitAllowingStateLoss(index);
//
//                RxBus.getDefault().post(new Message("MainActivity_index_" + index, ""));
//            }
//
//            @Override
//            public void onRepeat(int index) {
//            }
//        });
    }

    // 切换fragment
    protected Fragment switchFragment(Fragment to, String tag) {
        if (mContent != to) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(mContent).add(R.id.frameLayout, to, tag).commitAllowingStateLoss(); //
                // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(mContent).show(to).commitAllowingStateLoss(); //
                // 隐藏当前的fragment，显示下一个
            }
            mContent = to;
        }
        return mContent;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long exitTime;

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.toastLong(getResources().getString(R.string.string_exit_warn));
            exitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
        }

    }
}